import { ExceptionFilter, Catch, ArgumentsHost } from "@nestjs/common";
import { Response } from "express";
import { QueryFailedError } from "typeorm";

@Catch(QueryFailedError)
export class DuplicateFilter implements ExceptionFilter {
  catch(exception: QueryFailedError, host: ArgumentsHost) {
    if (exception.driverError.errno === 1062) {
      const ctx = host.switchToHttp();
      const response = ctx.getResponse<Response>();

      response.status(403).json({
        statusCode: 403,
        message: "对象已存在",
      });
    } else {
      const ctx = host.switchToHttp();
      const response = ctx.getResponse<Response>();
      console.error(exception);
      console.dir(exception.driverError);

      response.status(500).json({
        statusCode: 500,
        message: "数据库错误，请将错误上报到开发人员",
        error: {
          code: exception.driverError.code,
          sqlMessage: exception.driverError.sqlMessage,
          errno: exception.driverError.errno,
        },
      });
    }
  }
}
